import cv2
import numpy as np
import glob
import os
import math
from skimage import filters
import matplotlib as mpl
import math
mpl.use('tkagg')
import matplotlib.pyplot as plt
def Imgvar(img):                   # 求图像方差
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    dst=cv2.Laplacian(gray,cv2.CV_64F)    #拉普拉斯变换
    imgvar=dst.var()                      #得出方差
    return imgvar
def caltheta(path):
    img=cv2.imread(path)
    imgsize=img.shape[1]
    drawing = np.zeros(img.shape[:], dtype=np.uint8)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    if imgsize>500 and Imgvar(img)>600:
        gray=cv2.GaussianBlur(gray,(5,5),3)
    else:
        gray = cv2.GaussianBlur(gray, (5, 5), 1)
    thresh = filters.threshold_otsu(gray)
    edges=cv2.Canny(gray,thresh/3,thresh,7)
    lines = cv2.HoughLines(edges, 1, np.pi / 180, int(thresh), imgsize / 11)
    while (lines.shape[0])>100:
        gray = cv2.GaussianBlur(gray, (9, 9), 5)
        thresh = filters.threshold_otsu(gray)
        edges = cv2.Canny(gray,thresh/2, thresh,7)
        lines = cv2.HoughLines(edges, 1, np.pi / 180, int(thresh), imgsize / 11)
    arr=[]
    for line in lines:
        rho=line[0][0]
        theta1=line[0][1]
        a = np.cos(theta1)
        b = np.sin(theta1)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 1000 * (-b))
        y1 = int(y0 + 1000 * (a))
        x2 = int(x0 - 1000 * (-b))
        y2 = int(y0 - 1000 * (a))
        if  (x2-x1)!=0:
            theta=(y1-y2)/(x2-x1)
            if abs(theta)<0.8:
                cv2.line(drawing, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA)
                theta=math.atan(theta)*180/np.pi
                arr.append(abs(theta))
    # cv2.namedWindow('d',0)
    # cv2.imshow('d',drawing)
    # cv2.waitKey()
    iwpath=path.replace('.jpg','.png')
    (counts,bins,patch)=plt.hist(arr, 5)
    plt.xlabel('theta')
    plt.xlim(0, 39)
    plt.ylabel('Frequency')
    plt.title('theta')
    # plt.show()
    positon= np.argwhere(counts == np.amax(counts))
    positon=positon.flatten().tolist()
    theta=[]
    Counts=0
    for i in positon:
        theta.append(bins[i])
        Counts+=counts[i]
    return theta,Counts/sum(counts)

def judge(thetas,counts):
    #print(max(thetas))
    if max(thetas)<15 and counts>0.5:
        return 1
    else :
        return 0
if __name__=='__main__':
    filepath = 'C:/Users/DELL/Desktop/shushida0322-421/shushida0322-421/new/*.jpg'
    allpath = glob.glob(filepath)
    for path in allpath:
        theta,counts=caltheta(path)
        #print(theta,counts)
        img=cv2.imread(path)
        if judge(theta,counts)==1:
            iwpath = path.replace('new', 'shuiping')
            cv2.imwrite(iwpath,img)
    # thetas,counts = caltheta('C:/Users/DELL/Desktop/new/shushida0330-692/marked/gsk00465.jpg')
    # print(thetas,counts)
    # print(math.atan(0.8)*180/np.pi)

